package t327.controller;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.HttpHeaders;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.deploy.net.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import t327.pojo.*;
import t327.pojo.font.FileData;
import t327.pojo.font.LuiTableEntity;
import t327.pojo.staff.StaffManagement;
import t327.pojo.staffView.StaffManagementView;
import t327.pojo.until.Result;
import t327.pojo.views.OrderListView;
import t327.pojo.views.SampleSheetListView;
import t327.service.iter.IClientService;
import t327.service.iter.ISampleSheetService;
import t327.service.iter.IStaffManageService;
import t327.service.iter.IStyleNumberService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;

@RestController
@RequestMapping("SampleSheet")
public class SampleSheetController {
    @Autowired
    private ISampleSheetService sampleSheetService;
    @Autowired
    private IClientService iClientService;
    @Autowired
    private IStyleNumberService styleNumberService;
    @Autowired
    private IStaffManageService staffManageService;

    @RequestMapping("queryAllSampleSheetList")//样板单列表
    private LuiTableEntity queryAllSampleSheetList(@RequestParam(value = "page") Integer pageNum, @RequestParam(value = "limit") Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        LuiTableEntity luiTableEntity = new LuiTableEntity<StaffManagementView>();
        PageInfo<SampleSheetListView> productSemesterViewPageInfo = new PageInfo<SampleSheetListView>(sampleSheetService.getAllSampleSheetList());
        List<SampleSheetListView> sheetListViews = productSemesterViewPageInfo.getList();
        long total = productSemesterViewPageInfo.getTotal();
        if(sheetListViews!=null&&sheetListViews.size()>0){
            luiTableEntity.setCode("0");
            luiTableEntity.setMsg("查询成功");
            luiTableEntity.setCount(total);
            luiTableEntity.setData(sheetListViews);
        }else{
            luiTableEntity.setCode("203");
            luiTableEntity.setMsg("查询失败");
        }
        System.out.println("1");
        System.out.println(sheetListViews);
        return   luiTableEntity;
    }

    @RequestMapping("getClientName")//下拉框获取客户信息
    public List<Client> getClientName() {
        return iClientService.queryAll();
    }

    @RequestMapping("getBoardMaker")//下拉框获取板师
    public List<StaffManagement> getBoardMaker() {
        return staffManageService.getAllBoardMaker();
    }

    @RequestMapping("getStylist")//下拉框获取板师
    public List<StaffManagement> getStylist() {
        return staffManageService.getAllStylist();
    }

    @RequestMapping("toSampleSheetAudit")//根据样板单号查询详细信息
    public String  toSampleSheetAudit(HttpServletRequest request, Long sampleSheetId,Long styleNumberId){
        HttpSession session = request.getSession();
        session.setAttribute("sampleSheetId",sampleSheetId);
        session.setAttribute("styleNumberId",styleNumberId);
        return "manufacture/technicalDivision/sampleSheetAudit";
    }

    @RequestMapping("changeSubmit")//提交审核
    public String changeSubmit(Long sampleSheetId) {
        System.out.println("-=-=-=-");
        System.out.println(sampleSheetId);
        System.out.println("-=-=-=-");
        int i = sampleSheetService.updateSubmitStatus(sampleSheetId);
        if (i>0){
            return "success";
        }else {
            return "fail";
        }
    }

    @RequestMapping("addStyleNumber")//添加款号
    public Result addStyleNumber(@RequestBody StyleNumber styleNumber) {
        return styleNumberService.addStyleNumber(styleNumber);
    }

    @RequestMapping("querySampleSheetById")//根据Id获取详细信息
    public SampleSheetListView querySampleSheetById(Long sampleSheetId) {
        return sampleSheetService.getSampleSheetById(sampleSheetId);
    }

    @RequestMapping("queryAllMaterials")//根据Id获取主面料信息
    private LuiTableEntity queryAllMaterials(@RequestParam(value = "page") Integer pageNum, @RequestParam(value = "limit") Integer pageSize,HttpServletRequest request) {
        PageHelper.startPage(pageNum,pageSize);
        String sampleSheetIdString = request.getParameter("sampleSheetId");
        Long sampleSheetId = Long.parseLong(sampleSheetIdString);
        LuiTableEntity luiTableEntity = new LuiTableEntity<StaffManagementView>();
        PageInfo<SampleSheetAndMaterials> productSemesterViewPageInfo = new PageInfo<SampleSheetAndMaterials>(sampleSheetService.getAllMaterialsById(sampleSheetId));
        List<SampleSheetAndMaterials> materialsList = productSemesterViewPageInfo.getList();
        long total = productSemesterViewPageInfo.getTotal();
        if(materialsList!=null&&materialsList.size()>0){
            luiTableEntity.setCode("0");
            luiTableEntity.setMsg("查询成功");
            luiTableEntity.setCount(total);
            luiTableEntity.setData(materialsList);
        }else{
            luiTableEntity.setCode("203");
            luiTableEntity.setMsg("查询失败");
        }
        System.out.println("1");
        System.out.println(materialsList);
        return   luiTableEntity;
    }

    @RequestMapping("queryAllMaterials2")//根据Id获取主面料信息
    private LuiTableEntity queryAllMaterials2(@RequestParam(value = "page") Integer pageNum, @RequestParam(value = "limit") Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        LuiTableEntity luiTableEntity = new LuiTableEntity<StaffManagementView>();
        PageInfo<SampleSheetAndMaterials> productSemesterViewPageInfo = new PageInfo<SampleSheetAndMaterials>(sampleSheetService.getAllMaterials());
        List<SampleSheetAndMaterials> materialsList = productSemesterViewPageInfo.getList();
        long total = productSemesterViewPageInfo.getTotal();
        if(materialsList!=null&&materialsList.size()>0){
            luiTableEntity.setCode("0");
            luiTableEntity.setMsg("查询成功");
            luiTableEntity.setCount(total);
            luiTableEntity.setData(materialsList);
        }else{
            luiTableEntity.setCode("203");
            luiTableEntity.setMsg("查询失败");
        }
        System.out.println("1");
        System.out.println(materialsList);
        return   luiTableEntity;
    }

    @RequestMapping("queryAllLngredients")//根据Id获取辅料信息
    private LuiTableEntity queryAllLngredients(@RequestParam(value = "page") Integer pageNum, @RequestParam(value = "limit") Integer pageSize,HttpServletRequest request) {
        PageHelper.startPage(pageNum,pageSize);
        String sampleSheetIdString = request.getParameter("sampleSheetId");
        Long sampleSheetId = Long.parseLong(sampleSheetIdString);
        LuiTableEntity luiTableEntity = new LuiTableEntity<StaffManagementView>();
        PageInfo<SampleSheetAndMaterials> productSemesterViewPageInfo = new PageInfo<SampleSheetAndMaterials>(sampleSheetService.getAllLngredientsById(sampleSheetId));
        List<SampleSheetAndMaterials> materialsList = productSemesterViewPageInfo.getList();
        long total = productSemesterViewPageInfo.getTotal();
        if(materialsList!=null&&materialsList.size()>0){
            luiTableEntity.setCode("0");
            luiTableEntity.setMsg("查询成功");
            luiTableEntity.setCount(total);
            luiTableEntity.setData(materialsList);
        }else{
            luiTableEntity.setCode("203");
            luiTableEntity.setMsg("查询失败");
        }
        System.out.println("1");
        System.out.println(materialsList);
        System.out.println(luiTableEntity);
        return   luiTableEntity;
    }

    @RequestMapping("queryAllLngredients2")//根据Id获取辅料信息
    private LuiTableEntity queryAllLngredients2(@RequestParam(value = "page") Integer pageNum, @RequestParam(value = "limit") Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        LuiTableEntity luiTableEntity = new LuiTableEntity<StaffManagementView>();
        PageInfo<SampleSheetAndMaterials> productSemesterViewPageInfo = new PageInfo<SampleSheetAndMaterials>(sampleSheetService.getAllLngredients());
        List<SampleSheetAndMaterials> materialsList = productSemesterViewPageInfo.getList();
        long total = productSemesterViewPageInfo.getTotal();
        if(materialsList!=null&&materialsList.size()>0){
            luiTableEntity.setCode("0");
            luiTableEntity.setMsg("查询成功");
            luiTableEntity.setCount(total);
            luiTableEntity.setData(materialsList);
        }else{
            luiTableEntity.setCode("203");
            luiTableEntity.setMsg("查询失败");
        }
        System.out.println("1");
        System.out.println(materialsList);
        return   luiTableEntity;
    }

    @RequestMapping("addSampleSheet")
    public String addSampleSheet(@RequestBody SampleSheet sampleSheet) {
        Random random = new Random();// 创建一个 Random 对象
        long timestamp = System.currentTimeMillis();// 获取当前时间戳
        int styleNumber1=0;
            int randomNumber = random.nextInt(90) + 10;
        String result = "YBD" +timestamp+ randomNumber;// 在前面加上"KH"
        String result2 = "SJH" +timestamp+ randomNumber;// 在前面加上"KH"
        SampleSheet sampleSheet1 = new SampleSheet();
        sampleSheet1.setSampleSheetNum(result);
        sampleSheet1.setDesignNumber(result2);
        LocalDate currentDate = LocalDate.now();
        Date utilDate = Date.from(currentDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        sampleSheet1.setClientId(sampleSheet.getClientId()).setStyleNumberId(sampleSheet.getStyleNumberId()).setIngredientId(1L).setSuttle(sampleSheet.getSuttle())
        .setCardboardMaster(sampleSheet.getCardboardMaster()).setCarBoardEngineer(sampleSheet.getCarBoardEngineer()).setStylistId(sampleSheet.getStylistId()
        ).setStyleUnit(sampleSheet.getStyleUnit()).setRemark(sampleSheet.getRemark()).setPatternDate(utilDate).setFinishedPlateDate(sampleSheet.getFinishedPlateDate())
        .setProcessDecompositionDiagramSrc("asdffdasfa").setLogicDel(0L).setAuditStatus(0L).setModel(sampleSheet.getModel());
        int i = sampleSheetService.addSampleSheet(sampleSheet1);
        if (i>0){
            return "success";
        }else {
            return "fail";
        }
    }

    @RequestMapping("getStyleNumberList")
    private LuiTableEntity getStyleNumberList(@RequestParam(value = "page") Integer pageNum, @RequestParam(value = "limit") Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        LuiTableEntity luiTableEntity = new LuiTableEntity<StaffManagementView>();
        PageInfo<StyleNumber> pageInfo = new PageInfo<StyleNumber>(styleNumberService.getStyleNumberList());
        List<StyleNumber> sheetListViews = pageInfo.getList();
        long total = pageInfo.getTotal();
        if(sheetListViews!=null&&sheetListViews.size()>0){
            luiTableEntity.setCode("0");
            luiTableEntity.setMsg("查询成功");
            luiTableEntity.setCount(total);
            luiTableEntity.setData(sheetListViews);
        }else{
            luiTableEntity.setCode("203");
            luiTableEntity.setMsg("查询失败");
        }
        System.out.println("1");
        System.out.println(sheetListViews);
        return   luiTableEntity;
    }

    //笨方法
    // 7个尺码，7个请求
    @RequestMapping("querySSizeChart")//获取当前尺码数量
    public StyleNumSizeChart querySSizeChart(Long styleNumberId) {
        return sampleSheetService.StyleNumSizeByS(styleNumberId);
    }
    @RequestMapping("queryMSizeChart")//获取当前尺码数量
    public StyleNumSizeChart queryMSizeChart(Long styleNumberId) {
        return sampleSheetService.StyleNumSizeByM(styleNumberId);
    }
    @RequestMapping("queryLSizeChart")//获取当前尺码数量
    public StyleNumSizeChart queryLSizeChart(Long styleNumberId) {
        return sampleSheetService.StyleNumSizeByL(styleNumberId);
    }
    @RequestMapping("queryXLSizeChart")//获取当前尺码数量
    public StyleNumSizeChart queryXLSizeChart(Long styleNumberId) {
        return sampleSheetService.StyleNumSizeByXL(styleNumberId);
    }
    @RequestMapping("queryXXLSizeChart")//获取当前尺码数量
    public StyleNumSizeChart queryXXLSizeChart(Long styleNumberId) {
        return sampleSheetService.StyleNumSizeByXXL(styleNumberId);
    }
    @RequestMapping("query3XLSizeChart")//获取当前尺码数量
    public StyleNumSizeChart query3XLSizeChart(Long styleNumberId) {
        return sampleSheetService.StyleNumSizeBy3XL(styleNumberId);
    }
    @RequestMapping("query4XLSizeChart")//获取当前尺码数量
    public StyleNumSizeChart query4XLSizeChart(Long styleNumberId) {
        return sampleSheetService.StyleNumSizeBy4XL(styleNumberId);
    }
    @RequestMapping("getSheetListView")
    @ResponseBody
    public List<SampleSheetListView> orderListView(SampleSheetListView sampleSheetListView) {

        return sampleSheetService.getSheetListView(sampleSheetListView);
    }
    // 阿里云OSS配置信息
    private static final String endpoint = "http://oss-cn-shanghai.aliyuncs.com";
    private static final String accessKeyId = "LTAI5tBRnidRkeL5WM6zQR6W";
    private static final String accessKeySecret = "UICQgFjMbztgwoL6DefmrOl6CEZi8X";
    private static final String bucketName = "jskss";
    private static final String uploadDir = "";
    //上传文件
    @RequestMapping("uploadFiles")
    @ResponseBody
    public List<String> uploadFiles(@RequestParam("file") List<MultipartFile> files) {
        List<String> filenames = new ArrayList<>();

        // 创建OSS客户端
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    continue;
                }

                // 构建上传文件在OSS中的唯一名称     //地址
                String ossFilename = uploadDir + file.getOriginalFilename();

                // 上传文件到OSS
                ossClient.putObject(bucketName, ossFilename, file.getInputStream());

                // 将上传成功的文件名添加到列表中
                filenames.add(ossFilename);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭OSS客户端
            ossClient.shutdown();
        }

        // 返回上传成功的文件名列表
        return filenames;
    }

    @RequestMapping("selectFileData")
    public LuiTableEntity getFileList() {

        LuiTableEntity<FileData> fileDataLuiTableEntity = new LuiTableEntity<FileData>();
// 创建OSSClient对象
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

// 查询Bucket中的文件列表
        ObjectListing objectListing = ossClient.listObjects(bucketName);

// 遍历文件列表
        List<OSSObjectSummary> objectSummaries = objectListing.getObjectSummaries();

        List<FileData> fileListData = new ArrayList<>();

        for (OSSObjectSummary objectSummary : objectSummaries) {
            String name = objectSummary.getKey();
            Long size = objectSummary.getSize();
            Date date = objectSummary.getLastModified();
            Double sizeDouble = size.doubleValue();
            String url = name;
            System.out.println("------------------------------------++++++++"+url);
// 将文件信息添加到列表中
            FileData fileData = new FileData(name, sizeDouble, date,url);
            fileListData.add(fileData);
        }
// 关闭OSSClient
        ossClient.shutdown();

        PageInfo<FileData> pageInfo = new PageInfo<FileData>(fileListData);
        List<FileData> fileData = pageInfo.getList();
        long total = pageInfo.getTotal();
        if (fileListData.size()>0&&fileListData!=null){
            fileDataLuiTableEntity.setCode("0");
            fileDataLuiTableEntity.setMsg("查询成功");
            fileDataLuiTableEntity.setCount(total);
            fileDataLuiTableEntity.setData(fileData);
            System.out.println("========================"+fileData);
        }else {
            fileDataLuiTableEntity.setCode("203");
            fileDataLuiTableEntity.setMsg("查询失败");
        }


        return fileDataLuiTableEntity;
    }

    //下载文件
    @RequestMapping("downloadTheFile")
    @ResponseBody
    public ResponseEntity<InputStreamResource> downloadFile(@RequestParam("filename") String filename, HttpServletResponse response) throws IOException {
        // 创建 OSSClient 对象
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 生成私有访问 URL
        Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000); // 设置 URL 的过期时间
        String objectKey = filename; // 假设文件名与对象键相同
        String privateUrl = ossClient.generatePresignedUrl(bucketName, objectKey, expiration).toString();

        // 关闭 OSSClient
        ossClient.shutdown();

        // 设置响应头
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");

        // 获取文件输入流
        InputStream inputStream = new java.net.URL(privateUrl).openStream();

        // 创建输入流资源对象
        InputStreamResource inputStreamResource = new InputStreamResource(inputStream);

        // 返回响应实体
        return ResponseEntity.ok()
                .body(inputStreamResource);
        }




    @RequestMapping("toDelStyleNumById")//根据Id删除未创建样板单的款号
    public Result toDelStyleNumById(Long styleNumberId) {
        /*System.out.println(styleNumberId);
        System.out.println("id is here");*/
        int i = styleNumberService.delStyleNumById(styleNumberId);
        if (i>0){
            return new Result(200,"删除成功",true,null);
        }else {
            return new Result(202,"删除失败",false,null);
        }
    }
}